// 和 count 有关的state
import { createSlice } from '@reduxjs/toolkit';
import axios from 'axios'

let conterStore = createSlice({
  name: "count", // action 命名空间  。  count/adduser   ---   product/adduser
  initialState: {  // 初始化state
    count: 0,
    list: []
  },
  reducers: {
    add(state, action) {
      console.log(action)
      state.count += action.payload;
    },
    minus(state, action) {
      state.count -= action.payload;
    },
    changeList(state, action) {
      state.list = action.payload
    }
  }
})

let reducer = conterStore.reducer;
let { add, minus, changeList } = conterStore.actions;

// 异步action必须在同步action之后书写；
export function asyncMinus(payload) {
  return function (dispatch) {
    setTimeout(() => {
      dispatch(minus(payload))
    }, 1000);
  }
}

export function asyncGetList() {
  return async function (dispatch) {
    let { data } = await axios.get("/api/getlist")
    //   console.log(res);
    dispatch(changeList(data))
  }
}



export { add, minus };
export default reducer;


